<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青云教育系统 - 教师端</title>
    <link rel="stylesheet" href="../../teacher.css">
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="brand">青云教育 · 教师端</div>
            <nav class="menu" id="menu">
                <button class="menu-item" data-view="profile" data-url="/index">教员信息及考勤</button>
                <button class="menu-item" data-view="schedule" data-url="/schedule">教师课表</button>
                <button class="menu-item" data-view="password" data-url="/password">修改密码</button>
                <button class="menu-item" data-view="students" data-url="/students">学生信息</button>
                <button class="menu-item" data-view="upload" data-url="/postmaterial">上传资料</button>
                <button class="menu-item" data-view="download" data-url="/downloadmaterial">下载资料</button>
                <button class="menu-item active" data-view="mymaterials" data-url="/mymaterials">我的资料</button>
            </nav>
        </aside>
        <main class="content">
            <header class="topbar">
                <div class="left">
                    <h1 id="view-title">我的资料</h1>
                </div>
                <div class="right">
                    <div class="user-info">
                        <img id="user-avatar" class="user-avatar" src="" alt="用户头像">
                        <span id="teacher-name" class="user-name"></span>
                    </div>
                    <button id="logoutBtn" class="btn btn-secondary">退出登录</button>
                </div>
            </header>

            <section id="view-mymaterials" class="view" style="display:block;">
                <div class="card">
                    <div class="card-header">
                        <div class="filters">
                            <div class="filter-group">
                                <label>资料分类：</label>
                                <select id="categoryFilter">
                                    <option value="">全部分类</option>
                                    <option value="教案">教案</option>
                                    <option value="课件">课件</option>
                                    <option value="习题">习题</option>
                                    <option value="复习资料">复习资料</option>
                                    <option value="考试资料">考试资料</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                            <div class="filter-group">
                                <label>适用年级：</label>
                                <select id="gradeFilter">
                                    <option value="">全部年级</option>
                                    <option value="高一">高一</option>
                                    <option value="高二">高二</option>
                                    <option value="高三">高三</option>
                                    <option value="通用">通用</option>
                                </select>
                            </div>
                            <div class="filter-group">
                                <label>适用科目：</label>
                                <select id="subjectFilter">
                                    <option value="">全部科目</option>
                                    <option value="数学">数学</option>
                                    <option value="语文">语文</option>
                                    <option value="英语">英语</option>
                                    <option value="物理">物理</option>
                                    <option value="化学">化学</option>
                                    <option value="生物">生物</option>
                                    <option value="历史">历史</option>
                                    <option value="地理">地理</option>
                                    <option value="政治">政治</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                            <div class="filter-group">
                                <label>搜索关键词：</label>
                                <input type="text" id="searchKeyword" placeholder="输入资料名称或描述搜索">
                            </div>
                            <button id="searchBtn" class="btn btn-primary">搜索</button>
                            <button id="refreshBtn" class="btn btn-secondary">刷新</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="materialList" class="material-list">
                            <!-- 资料列表将通过JavaScript动态生成 -->
                        </div>
                        <div id="materialEmpty" class="empty" style="display:none;">暂无上传的资料</div>
                        <div id="loading" class="loading" style="display:none;">加载中...</div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <script src="../../teacher.js"></script>
    <script>
        // 页面加载时验证登录状态
        document.addEventListener('DOMContentLoaded', function(){
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            
            // 检查用户是否已登录
            if (!userInfo || !userInfo.token || !userInfo.userDTO || 
                typeof userInfo.token !== 'string' || userInfo.token.trim() === '') {
                console.log('用户未登录，跳转到登录页');
                localStorage.removeItem('userInfo');
                localStorage.removeItem('userToken');
                window.location.href = '../../login.html';
                return;
            }
            
            // 验证token格式
            if (userInfo.token.length < 10) {
                console.log('Token格式无效，跳转到登录页');
                localStorage.removeItem('userInfo');
                localStorage.removeItem('userToken');
                window.location.href = '../../login.html';
                return;
            }
            
            console.log('用户已登录，页面正常加载');
        });
        
        // 确保退出登录功能正常工作
        document.addEventListener('DOMContentLoaded', function(){
            // 绑定退出登录按钮事件
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn && !logoutBtn.hasAttribute('data-bound')) {
                logoutBtn.setAttribute('data-bound', 'true');
                logoutBtn.addEventListener('click', function(e) {
                    console.log('退出登录按钮被点击（来自mymaterials页面）');
                    e.preventDefault();
                    if (typeof logout === 'function') {
                        logout();
                    } else {
                        console.error('logout函数未定义');
                    }
                });
            }
            
            // 菜单跳转逻辑
            const menu = document.getElementById('menu');
            if (menu) {
                console.log('菜单元素找到，绑定点击事件');
                menu.addEventListener('click', function(e){
                    console.log('菜单被点击');
                    const btn = e.target.closest('.menu-item');
                    if(!btn) {
                        console.log('没有找到菜单项');
                        return;
                    }
                    const view = btn.getAttribute('data-view');
                    console.log('点击的菜单项:', view);
                    
                    if(view === 'schedule') {
                        console.log('跳转到课表页面');
                        window.location.href = location.origin + '/teacher/schedule';
                    }
                    else if(view === 'password') {
                        console.log('跳转到修改密码页面');
                        window.location.href = location.origin + '/teacher/password';
                    }
                    else if(view === 'profile') {
                        console.log('跳转到首页');
                        window.location.href = '/index.html';
                    }
                    else if(view === 'upload') {
                        console.log('跳转到上传资料页面');
                        window.location.href = location.origin + '/teacher/postmaterial';
                    }
                    else if(view === 'download') {
                        console.log('跳转到下载资料页面');
                        window.location.href = location.origin + '/teacher/downloadmaterial';
                    }
                    else if(view === 'students') {
                        console.log('跳转到学生信息页面');
                        window.location.href = location.origin + '/teacher/students';
                    }
                    else if(view === 'mymaterials') {
                        console.log('刷新我的资料列表');
                        // 点击我的资料菜单时刷新列表
                        loadMaterialList();
                    }
                    else {
                        console.log('未知的菜单项:', view);
                    }
                });
            } else {
                console.error('菜单元素未找到！');
            }
            
            // 绑定搜索和刷新按钮
            document.getElementById('searchBtn').addEventListener('click', function() {
                loadMaterialList();
            });
            
            document.getElementById('refreshBtn').addEventListener('click', function() {
                document.getElementById('categoryFilter').value = '';
                document.getElementById('gradeFilter').value = '';
                document.getElementById('subjectFilter').value = '';
                document.getElementById('searchKeyword').value = '';
                loadMaterialList();
            });
            
            // 页面加载时调用一次资料列表接口
            loadMaterialList();
        });
        
        // 加载资料列表
        async function loadMaterialList() {
            try {
                showLoading(true);
                
                // 获取筛选条件
                const category = document.getElementById('categoryFilter').value;
                const grade = document.getElementById('gradeFilter').value;
                const subject = document.getElementById('subjectFilter').value;
                const keyword = document.getElementById('searchKeyword').value.trim();
                
                // 获取用户token
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token;
                
                if (!token) {
                    console.error('未找到用户token');
                    showEmptyMessage('请先登录');
                    return;
                }
                
                // 构建查询参数
                const params = new URLSearchParams();
                if (category) params.append('category', category);
                if (grade) params.append('grade', grade);
                if (subject) params.append('subject', subject);
                if (keyword) params.append('keyword', keyword);
                
                console.log('调用我的资料接口:', '/material/my-materials');
                console.log('查询参数:', params.toString());
                
                // 调用后端接口
                const response = await fetch(`/material/my-materials?${params.toString()}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    console.log('我的资料接口返回:', result);
                    
                    if (result.success && result.data) {
                        displayMaterialList(result.data);
                    } else {
                        console.error('接口返回失败:', result.message || '未知错误');
                        showEmptyMessage('获取资料列表失败');
                    }
                } else {
                    console.error('接口请求失败:', response.status);
                    showEmptyMessage('网络请求失败');
                }
            } catch (error) {
                console.error('调用我的资料接口异常:', error);
                showEmptyMessage('加载资料列表时发生错误');
            } finally {
                showLoading(false);
            }
        }
        
        // 显示资料列表
        function displayMaterialList(materialList) {
            const container = document.getElementById('materialList');
            const empty = document.getElementById('materialEmpty');
            
            container.innerHTML = '';
            empty.style.display = 'none';
            
            if (!materialList || materialList.length === 0) {
                showEmptyMessage('暂无上传的资料');
                return;
            }
            
            // 渲染资料列表
            materialList.forEach(material => {
                const materialItem = document.createElement('div');
                materialItem.className = 'item';
                materialItem.innerHTML = `
                    <div class="material-info">
                        <div class="material-title">${material.title || '未设置标题'}</div>
                        <div class="material-meta">
                            <span class="meta-item">分类：${material.category || '未分类'}</span>
                            <span class="meta-item">年级：${material.grade || '不限'}</span>
                            <span class="meta-item">科目：${material.subject || '不限'}</span>
                        </div>
                        <div class="material-description">${material.description || '暂无描述'}</div>
                        <div class="material-stats">
                            <span class="stat-item">上传时间：${formatDate(material.createTime)}</span>
                            <span class="stat-item">文件大小：${formatFileSize(material.fileSize)}</span>
                            <span class="stat-item">下载次数：${material.downloadCount || 0}</span>
                        </div>
                    </div>
                    <div class="material-actions">
                        <button class="btn btn-primary" onclick="downloadMaterial('${material.id}')">下载</button>
                        <button class="btn btn-warning" onclick="editMaterial('${material.id}')">编辑</button>
                        <button class="btn btn-danger" onclick="deleteMaterial('${material.id}')">删除</button>
                    </div>
                `;
                container.appendChild(materialItem);
            });
        }
        
        // 下载资料
        async function downloadMaterial(materialId) {
            try {
                console.log('下载资料:', materialId);
                
                // 获取用户token
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token;
                
                if (!token) {
                    alert('请先登录');
                    return;
                }
                
                // 调用下载接口
                const response = await fetch(`/material/download/${materialId}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': token
                    }
                });
                
                if (response.ok) {
                    // 获取文件名
                    const contentDisposition = response.headers.get('Content-Disposition');
                    let filename = 'download';
                    if (contentDisposition) {
                        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                        if (filenameMatch && filenameMatch[1]) {
                            filename = filenameMatch[1].replace(/['"]/g, '');
                        }
                    }
                    
                    // 创建下载链接
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    console.log('下载成功');
                    
                    // 刷新列表以更新下载次数
                    setTimeout(() => {
                        loadMaterialList();
                    }, 1000);
                } else {
                    console.error('下载失败:', response.status);
                    alert('下载失败，请重试');
                }
            } catch (error) {
                console.error('下载资料异常:', error);
                alert('下载时发生错误');
            }
        }
        
        // 编辑资料
        function editMaterial(materialId) {
            console.log('编辑资料:', materialId);
            // 这里可以实现编辑功能，比如跳转到编辑页面或弹出编辑对话框
            alert('编辑功能待实现');
        }
        
        // 删除资料
        async function deleteMaterial(materialId) {
            if (!confirm('确定要删除这个资料吗？删除后无法恢复。')) {
                return;
            }
            
            try {
                console.log('删除资料:', materialId);
                
                // 获取用户token
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token;
                
                if (!token) {
                    alert('请先登录');
                    return;
                }
                
                // 调用删除接口
                const response = await fetch(`/material/delete/${materialId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': token
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        alert('删除成功');
                        // 刷新列表
                        loadMaterialList();
                    } else {
                        alert('删除失败：' + (result.message || '未知错误'));
                    }
                } else {
                    console.error('删除失败:', response.status);
                    alert('删除失败，请重试');
                }
            } catch (error) {
                console.error('删除资料异常:', error);
                alert('删除时发生错误');
            }
        }
        
        // 显示空状态消息
        function showEmptyMessage(message) {
            const container = document.getElementById('materialList');
            const empty = document.getElementById('materialEmpty');
            
            container.innerHTML = '';
            empty.textContent = message;
            empty.style.display = 'block';
        }
        
        // 显示/隐藏加载状态
        function showLoading(show) {
            const loading = document.getElementById('loading');
            if (loading) {
                loading.style.display = show ? 'block' : 'none';
            }
        }
        
        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
            } catch (error) {
                return dateString;
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (!bytes || bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html>
